package zhongbo.java.air.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zhongbo.java.air.mapper.AirFlightPathMapper;
import zhongbo.java.air.common.vo.PageVo;
import zhongbo.java.air.listener.RedisLogChaneIPublisher;
import zhongbo.java.air.model.AirFlightPath;
import zhongbo.java.air.service.AirFlightPathService;
import zhongbo.java.air.config.RedisListenerConfig;

import javax.annotation.Resource;
import java.util.*;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 飞行轨迹记录表(AirFlightPath)表服务实现类
 *
 * @author makejava
 * @since 2025-04-02 09:30:55
 */
@Service("airFlightPathService")
public class AirFlightPathServiceImpl implements AirFlightPathService<AirFlightPath> {
    @Resource
    private AirFlightPathMapper airFlightPathMapper;

    @Autowired
    private RedisLogChaneIPublisher redisLogChaneIPublisher;

    @Autowired
    private ObjectMapper objectMapper; // 添加 ObjectMapper 实例

    /**
     * 通过ID查询单条数据
     *
     * @param entityId 主键
     * @return 实例对象
     */
//    @Override
//    public AirFlightPath queryById(String id) throws Exception {
//        if (id == null){
//            throw new Exception("id不能为空");
//        }
//        Optional<AirFlightPath> airFlightPathOptional = Optional.ofNullable(this.airFlightPathMapper.selectById(id));
//        if (!airFlightPathOptional.isPresent()){
//            throw new Exception("id不存在");
//        }
//        AirFlightPath airFlightPath = airFlightPathOptional.get();
//        redisLogChaneIPublisher.publish(RedisListenerConfig.LOG_CHANGE, "查询的ID是: " + id);
//        return airFlightPath;
//    }
    @Override
    public AirFlightPath findOne(String entityId) throws Exception {
        if (entityId == null){
            throw new Exception("id不能为空");
        }
        Optional<AirFlightPath> airFlightPathOptional = Optional.ofNullable(this.airFlightPathMapper.selectById(entityId));
        if (!airFlightPathOptional.isPresent()){
            throw new Exception("id不存在");
        }
        AirFlightPath airFlightPath = airFlightPathOptional.get();
        redisLogChaneIPublisher.publish(RedisListenerConfig.LOG_CHANGE, "查询的ID是: " + entityId);
        return airFlightPath;
    }

//    /**
//     * 分页查询
//     *
//     * @param page 页码
//     * @param pageSize 分页大小
//     * @param icao icao_code
//     * @param startTime 开始时间
//     * @param endTime 结束时间
//     * @param keyword 关键字
//     * @param fields 字段
//     * @param oderByField 排序字段
//     * @param orderByAsc 是否升序
//     * @return 查询结果
//     */
//    @Override
//    public PageVo<AirFlightPath> findPage(Integer page, Integer pageSize, String icao, String startTime, String endTime, String keyword, String fields, String oderByField, Boolean orderByAsc) {
//        // 参数校验
//        if (page == null || pageSize == null) {
//            throw new IllegalArgumentException("页码和大小不能为空");
//        }
//
//        // 计算偏移量
//        int offset = (page - 1) * pageSize;
//
//        // 调用 Mapper 方法查询数据
//        List<AirFlightPath> airFlightList = airFlightPathMapper.findPage(page, pageSize, icao, startTime, endTime, keyword, fields, oderByField, orderByAsc);
//
//        // 获取总记录数
//        long total = airFlightPathMapper.countByCondition(icao, startTime, endTime, keyword);
//
//        // 返回分页结果
//        return new zhongbo.java.air.common.vo.PageVo<>(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, pageSize, total).setRecords(airFlightList));
//    }


    @Override
    public PageVo<AirFlightPath> findPage(int page, int pageSize, String keyword, String fields, String oderByField, boolean orderByAsc) {
        QueryWrapper<AirFlightPath> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(keyword) && StrUtil.isNotBlank(fields)) {
            String[] fieldsArray = fields.split(",");
            for (String field : fieldsArray) {
                queryWrapper.or().like(StrUtil.toUnderlineCase(field),keyword);
            }
        }
        IPage<AirFlightPath> pageParam = new Page<>(page, pageSize);
        IPage airAlertZoneIPage = airFlightPathMapper.selectPage(pageParam,queryWrapper);
        return new PageVo<>(airAlertZoneIPage);
    }


    /**
     * 新增数据
     *
     * @param entity 实例对象
     * @return 实例对象
     */
//    @Override
//    public AirFlightPath insert(AirFlightPath airFlightPath) throws Exception {
//        if (airFlightPath == null){
//            throw new Exception("新增失败");
//        }
//        // 确保默认值
//        airFlightPath.ensureDefaults();
//        // 验证字段有效性
//        validateFields(airFlightPath);
//        // 检查 id 是否已存在，如果存在则生成新的 id
//        while (airFlightPathMapper.selectById(airFlightPath.getId()) != null) {
//            airFlightPath.setId(UUID.randomUUID().toString());
//        }
//        // 确保 icao_code 字段不为空
//        if (airFlightPath.getIcaoCode() == null) {
//            throw new Exception("icao_code 不能为空");
//        }
//        this.airFlightPathMapper.insert(airFlightPath);
//
//        // 使用 HashMap 替代 Map.of
//        Map<String, Object> messageMap = new HashMap<>();
//        messageMap.put("action", "insert");
//        messageMap.put("id", airFlightPath.getId());
//        String message = objectMapper.writeValueAsString(messageMap);
//        redisLogChaneIPublisher.publish(RedisListenerConfig.LOG_CHANGE, message);
//
//        // 添加广播到 INST_FLIGHT_PATH 频道
//        Map<String, Object> instFlightPathMessageMap = new HashMap<>();
//        instFlightPathMessageMap.put("action", "insert");
//        instFlightPathMessageMap.put("id", airFlightPath.getId());
//        String instFlightPathMessage = objectMapper.writeValueAsString(instFlightPathMessageMap);
//        redisLogChaneIPublisher.publish(RedisListenerConfig.INST_FLIGHT_PATH, instFlightPathMessage);
//
//        return airFlightPath;
//    }

    @Override
    public AirFlightPath add(AirFlightPath entity) throws Exception {
        if (entity == null){
            throw new Exception("新增失败");
        }
        // 确保默认值
        entity.ensureDefaults();
        // 验证字段有效性
        validateFields(entity);
        // 检查 id 是否已存在，如果存在则生成新的 id
        while (airFlightPathMapper.selectById(entity.getId()) != null) {
            entity.setId(UUID.randomUUID().toString());
        }
        // 确保 icao_code 字段不为空
        if (entity.getIcaoCode() == null) {
            throw new Exception("icao_code 不能为空");
        }
        this.airFlightPathMapper.insert(entity);

        // 使用 HashMap 替代 Map.of
        Map<String, Object> messageMap = new HashMap<>();
        messageMap.put("action", "insert");
        messageMap.put("id", entity.getId());
        String message = objectMapper.writeValueAsString(messageMap);
        redisLogChaneIPublisher.publish(RedisListenerConfig.LOG_CHANGE, message);

        // 添加广播到 INST_FLIGHT_PATH 频道
        Map<String, Object> instFlightPathMessageMap = new HashMap<>();
        instFlightPathMessageMap.put("action", "insert");
        instFlightPathMessageMap.put("id", entity.getId());
        String instFlightPathMessage = objectMapper.writeValueAsString(instFlightPathMessageMap);
        redisLogChaneIPublisher.publish(RedisListenerConfig.INST_FLIGHT_PATH, instFlightPathMessage);

        return entity;
    }

    /**
     * 修改数据
     *
     * @param edit 实例对象
     * @return 实例对象
     */
//    @Override
//    public AirFlightPath update(AirFlightPath airFlightPath) throws Exception {
//        if (airFlightPath == null){
//            throw new Exception("更新失败");
//        }
//        // 确保默认值
//        airFlightPath.ensureDefaults();
//        // 验证字段有效性
//        validateFields(airFlightPath);
//        // 检查 id 是否存在
//        if (airFlightPathMapper.selectById(airFlightPath.getId()) == null) {
//            throw new Exception("ID 不存在");
//        }
//        this.airFlightPathMapper.updateById(airFlightPath);
//        // 使用 HashMap 替代 Map.of
//        Map<String, Object> messageMap = new HashMap<>();
//        messageMap.put("action", "update");
//        messageMap.put("id", airFlightPath.getId());
//        String message = objectMapper.writeValueAsString(messageMap);
//        redisLogChaneIPublisher.publish(RedisListenerConfig.LOG_CHANGE, message);
//        return airFlightPath;
//    }
    @Override
    public AirFlightPath edit(AirFlightPath edit) throws Exception {
        if (edit == null){
            throw new Exception("更新失败");
        }
        // 确保默认值
        edit.ensureDefaults();
        // 验证字段有效性
        validateFields(edit);
        // 检查 id 是否存在
        if (airFlightPathMapper.selectById(edit.getId()) == null) {
            throw new Exception("ID 不存在");
        }
        this.airFlightPathMapper.updateById(edit);
        // 使用 HashMap 替代 Map.of
        Map<String, Object> messageMap = new HashMap<>();
        messageMap.put("action", "update");
        messageMap.put("id", edit.getId());
        String message = objectMapper.writeValueAsString(messageMap);
        redisLogChaneIPublisher.publish(RedisListenerConfig.LOG_CHANGE, message);
        return edit;
    }

    /**
     * 通过主键删除数据
     *
     * @param entityId 主键
     * @return 是否成功
     */
//    @Override
//    public boolean deleteById(String id) throws Exception {
//        if (id == null){
//            throw new Exception("id不能为空");
//        }
//        boolean result = this.airFlightPathMapper.deleteById(id) > 0;
//        if (result) {
//            redisLogChaneIPublisher.publish(RedisListenerConfig.LOG_CHANGE, "删除的ID是: " + id); // 使用 LOG_CHANGE 常量
//        }
//        return result;
//    }
    @Override
    public boolean delete(String entityId) throws Exception {
        if (entityId == null){
            throw new Exception("id不能为空");
        }
        boolean result = this.airFlightPathMapper.deleteById(entityId) > 0;
        if (result) {
            redisLogChaneIPublisher.publish(RedisListenerConfig.LOG_CHANGE, "删除的ID是: " + entityId); // 使用 LOG_CHANGE 常量
        }
        return result;
    }

    // 添加字段验证方法
    private void validateFields(AirFlightPath airFlightPath) throws Exception {
        if (airFlightPath.getId() == null) {
            throw new Exception("ID不能为空");
        }
        if (airFlightPath.getTimestamp() == null) {
            throw new Exception("时间戳不能为空");
        }
        if (airFlightPath.getSourceType() == null) {
            throw new Exception("数据源类型不能为空");
        }
    }
}